package com.yoki.cloud.common.protocol.radius.attribute.attr.type;


import com.yoki.cloud.common.protocol.radius.attribute.attr.RadiusMsgAttr;

/**
 * @author Sky$
 * @Description: TODO
 * @date 2018/1/16$ 17:59$
 */
public abstract class IntegerTypeAttr extends RadiusMsgAttr<Integer> {

    private static final int INTEGER_ATTRIBUTE_BYTES_LENGTH = 4;

    @Override
    protected Integer parseValue(byte[] input) {
        if (null == input || input.length != INTEGER_ATTRIBUTE_BYTES_LENGTH) {
            throw new IndexOutOfBoundsException("Integer attribute value must not null and length must equal " + INTEGER_ATTRIBUTE_BYTES_LENGTH + " !!!");
        }
        Integer value = 0;
        for (int i = 0; i < INTEGER_ATTRIBUTE_BYTES_LENGTH; i++) {
            value = value | ((input[i] & 0xff) << ((INTEGER_ATTRIBUTE_BYTES_LENGTH - 1 - i) * 8));
        }
        return value;
    }

    @Override
    protected byte[] getValueBytes() {
        byte[] bytes = new byte[INTEGER_ATTRIBUTE_BYTES_LENGTH];
        for (int i = 0; i < INTEGER_ATTRIBUTE_BYTES_LENGTH; i++) {
            bytes[i] = (byte) ((value >> ((INTEGER_ATTRIBUTE_BYTES_LENGTH - 1 - i) * 8)) & 0xff);
        }
        return bytes;
    }

}
